from flask import Flask
import os

from functools import wraps

def cached(ttl=300):
    def decorator(f):
        cache = {}
        @wraps(f)
        def wrapper(*args, **kwargs):
            key = f"{args}_{kwargs}"
            if key in cache and time.time() < cache[key]['expire']:
                return cache[key]['response']
            
            response = f(*args, **kwargs)
            cache[key] = {
                'response': response,
                'expire': time.time() + ttl
            }
            return response
        return wrapper
    return decorator

@app.route('/scratchwork/<id>.sb3')
@cached(ttl=86400)
def scratch_vm_viewer2(id):
    return send_from_directory(
        app.config['SCRATCH_FOLDER'],
        f'{id}.sb3',
        mimetype='application/x-scratch-project'
    )
